package com.aji.silk.controller;

import com.aji.allcommon.result.Result;
import com.aji.allcommon.service.FileStorageService;
import com.aji.allcommon.utills.MultipartFileUtill;
import com.aji.silk.domain.Silk;
import com.aji.silk.service.SilkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/silk")
@Api(tags = "丝绸残留物模块")
@CrossOrigin
@RequiredArgsConstructor
public class SilkController {

    private final SilkService silkService;
    private final FileStorageService fileStorageService;

    @ApiOperation("图片转url地址")
    @PostMapping("/imgToUrl")
    public Result imgToUrl(MultipartFile imgFile) throws IOException {
        String originalFilename = imgFile.getOriginalFilename();
        String simpFileName = originalFilename.substring(0, originalFilename.length() - 4) + ".jpg";
        File fileimg = File.createTempFile("temp", null);
        imgFile.transferTo(fileimg);
        FileInputStream simpJpgFile = MultipartFileUtill.multipartTifToJpgFileInputStream(fileimg);
        String accessSimpFileName = fileStorageService.uploadFile("img/jpg", simpFileName, simpJpgFile, "img/jpg");
        return Result.success(accessSimpFileName);
    }
    @ApiOperation("新增样品信息")
    @PostMapping()
    public Result save(@RequestBody Silk entity){
        entity.setCreateTime(new Date());
        silkService.save(entity);
        return Result.success();
    }
    @ApiOperation("删除样品信息")
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        silkService.removeByIds(ids);
        return Result.success("删除成功！");
    }
    @ApiOperation("修改样品信息")
    @PutMapping()
    public Result updateById(@RequestBody Silk entity){
        System.out.println(entity);
        silkService.updateById(entity);
        return Result.success();
    }
    @ApiOperation("查询样品信息 根据id")
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        return Result.success(silkService.getById(id));
    }

    @ApiOperation("查询全部样品信息")
    @GetMapping("/list")
    public Result list(){
        return Result.success(silkService.list(null));
    }

    @ApiOperation("获取数据总量")
    @GetMapping("/count")
    public Result count(){
        int count = Math.toIntExact(silkService.count());
        return Result.success(count);
    }
}
